package com.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class TextFileUtil {
	protected String fileName;

	TextFileUtil(String filename) {
		fileName = filename;
	}

	public String getFile() {
		return fileName;
	}

	public ArrayList<String> readAllLine() {

		return readSomeLine(0, -1);
	}

	public ArrayList<String> readSomeLine(int from, int to) {
		ArrayList<String> temp = new ArrayList<String>();
		
		int i = 0;
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(fileName));
			try {
				StringBuilder sb = new StringBuilder();
				String line = br.readLine();

				while (line != null) {
					if (i >= from - 1 && (to == -1 || i <= to)) {
						temp.add(line);
					}
					i++;
					sb.append(line);
					sb.append(System.lineSeparator());
					line = br.readLine();
				}
				//String everything = sb.toString();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return temp;
	}

	public static ArrayList<String> readSomeLine(String filename, int from, int to) {
		return new TextFileUtil(filename).readSomeLine(from, to); 
	}
	
	public static ArrayList<String> readAllLine(String filename) {
		return new TextFileUtil(filename).readAllLine(); 
	}
	
	public static void writeLog(String[] lines) {
		BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            for (String item : lines) {
            	writer.write(item);
            	writer.write("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }

	}
	
	public static String[] convertToArray(ArrayList<String> src) {
		String[] dest = new String[src.size()];
		int i = 0;
		for (String item : src) {
			dest[i] = item;
			i++;
		}
		
		return dest;
	}
}
